package com.meihua.baoleyi.ui;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.utils.ListUtils;

import java.util.HashMap;
import java.util.Map;
/**
 * Created by liming on 17/10/17
 */
public class MsgInfoH5Activity extends BaseActivity {

    private static final String TAG = MsgInfoH5Activity.class.getSimpleName();

    private WebView webView;
    private View main;
    private ProgressBar jump_pb;
    private HashMap<String, String> hashMap = new HashMap<>();
    private boolean favorite;
    private String stores_id;
    private String goods_id;
    private String order_num;
    private String status;
    private String Url;
    /**
     * Java方法，启动计算器界面
     */
    @JavascriptInterface
    public void backHome() {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            webView.loadUrl("javascript:" + "history_back()");
            if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {  //表示按返回键
                webView.goBack();   //后退
                //webview.goForward();//前进
                return true;    //已处理
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            webView.loadUrl("javascript:" + "history_back()");
            if (webView.canGoBack()) {  //表示按返回键
                webView.goBack();   //后退
                //webview.goForward();//前进
                return true;    //已处理
            }
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private String title;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_h5);
        ImageView text_back = (ImageView) findViewById(R.id.text_back);
        TextView text_title = (TextView) findViewById(R.id.text_title);
        main = findViewById(R.id.main);
        jump_pb = (ProgressBar) findViewById(R.id.pb_jump);
        title = getIntent().getStringExtra("title");
        status = getIntent().getStringExtra("status");
        stores_id = getIntent().getStringExtra("stores_id");
        goods_id = getIntent().getStringExtra("goods_id");
        order_num = getIntent().getStringExtra("order_num");
        Url = getIntent().getStringExtra("Url");
      //  Acp.getInstance(this).request(new AcpOptions.Builder()
                   //     .setPermissions(Manifest.permission.ACCESS_FINE_LOCATION)
                   //     .build(),
//                new AcpListener() {
////                    @Override
////                    public void onGranted() {
////                        setLocation();
////                    }
//
////                    @Override
////                    public void onDenied(List<String> permissions) {
////                        Toast.makeText(MsgInfoH5Activity.this,"权限拒绝",Toast.LENGTH_LONG).show();
////                    }
//                });
        text_title.setText(title);
        final String url = getIntent().getStringExtra("URL");
        webView = (WebView) findViewById(R.id.webView);
        webView.addJavascriptInterface(this, "nanzhu");
        //new MobclickAgentJSInterface(this, webView, new MyWebChromeClient());
        Map<String, String> extraHeaders = new HashMap<>();
        //extraHeaders.put(AuthStringRequest.AUTH_TOKEN_KEY, SharePref.getUserToken(AppContext.getContext()));
        extraHeaders.put("app-version", ListUtils.getAppVersionName(getApplicationContext()));

        webView.setWebViewClient(new MyWebViewClient());
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        // 建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT,无网络时，使用LOAD_CACHE_ELSE_NETWORK
        if (ListUtils.isNetworkAvailable(getApplicationContext()) == true) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 设置缓存模式
        } else {
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 设置缓存模式
        }
        // 开启DOM storage API 功能
        webView.getSettings().setDomStorageEnabled(true);
        // 开启database storage API功能
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        String cacheDirPathw = getFilesDir().getAbsolutePath()
                + ListUtils.APP_CACHE_DIRNAME;
        // 设置数据库缓存路径
        webView.getSettings().setDatabasePath(cacheDirPathw); // API 19 deprecated
        // 设置Application caches缓存目录
        webView.getSettings().setAppCachePath(cacheDirPathw);
        // 开启Application Cache功能
        webView.getSettings().setAppCacheEnabled(true);
//        webView.addJavascriptInterface(new JsInterface(), "liangliang");
       // text_back.setOnClickListener(this);
        if (title.equals("订单详情")) {
           // refresh();
        } else {
            webView.loadUrl(url, extraHeaders);
        }

    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        if (webView != null)
            webView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (webView != null) {
            webView.onResume();
            webView.reload();
        }
        super.onResume();
    }

    /**
     * Java方法，启动打开电话
     */
    @JavascriptInterface
    public void callPhone(String url) {

    }
    @JavascriptInterface
    public void goProfileInfo(String profileId,String title){

    }
    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            jump_pb.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            jump_pb.setVisibility(View.GONE);
            webView.setVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.removeAllViews();

            return false;
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                       SslError error) {
            handler.proceed(); // 接受所有网站的证书
        }

    }

}
